package com.cmxh.cloundnote.service;


import com.cmxh.cloundnote.mapper.UserMapper;
import com.cmxh.cloundnote.pojo.Upwd;
import com.cmxh.cloundnote.pojo.User;
import com.cmxh.cloundnote.util.Code;
import com.cmxh.cloundnote.util.Md5Util;


import com.cmxh.cloundnote.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceimpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public int saveUser(User user) {
        // 页面传递过来的密码是明文  但是数据库要加密的 所以此时要把页面传递过来的密码进行加
        String miwen = Md5Util.encrypt(user.getPassword());
        System.out.println(miwen);
        // 把user中的密码改成密文
        user.setPassword(miwen);

        return userMapper.saveUser(user);
    }

    @Override
    public Result login(User user) {
        User user1 = userMapper.findUsesByUname(user.getUsername());
        if (user1==null){
            return new Result(Code.GET_ERR,"用户名不存在");
        }else {
            String miwen = Md5Util.encrypt(user.getPassword());
            if (miwen.equals(user1.getPassword())){
                return new Result(Code.GET_OK,user1,"登录成功");
            }else {
                return new Result(Code.GET_ERR,"密码输入错误");
            }
        }

    }

    @Override
    public Result updatePassword(Upwd user) {


        // 添加空值校验
        if (user.getNewpwd() == null || user.getOldpwd() == null) {
            return new Result(Code.UPDATE_ERR, "密码字段不能为空");
        }

        // 调整比较顺序（安全调用equals）
        if (user.getNewpwd().equals(user.getOldpwd())) {
            return new Result(Code.UPDATE_ERR, "新旧密码不能相同");
        }
        else {
            //将新密码和旧密码进行加密
            String old= Md5Util.encrypt(user.getOldpwd());
            String xin= Md5Util.encrypt(user.getNewpwd());
            //重新加到这个对象中
            user.setNewpwd(xin);
            user.setPassword(xin);
            user.setOldpwd(old);
            //将这个对象传到mapper层进行修改
            int i = userMapper.updatePassword(user);
            if (i>0){
                return new Result(Code.UPDATE_OK,"修改成功");
            }else {
                return new Result(Code.UPDATE_ERR,"修改失败");
            }
        }
    }
/**修改昵称和邮箱**/
    @Override
    public Result updateUser(User user) {
        //将这个对象传到mapper层进行修改
        int i = userMapper.updateUser(user);
        if (i>0){
            return new Result(Code.UPDATE_OK,"修改成功");
        }else {
            return new Result(Code.UPDATE_ERR,"修改失败");
        }
    }

    @Override
    public int tx(User user) {
        return userMapper.tx(user);
    }


}
